/**
 * @(#)TaskViewActivity.java        1.0 2/28/12
 * 
 * Copyright (c) 2012 public static droid main
 * Georgia Institute of Technology, Atlanta, GA
 * All rights reserved.
 */

package edu.gatech.oad.publicstaticdroidmain.taskmanager.ui;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.TaskManagerDBFacade;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task.TaskAttribute;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * An Android activity that allows a user to view a list of all of 
 * their Tasks.
 * 
 * @version 1.0 Feb 22 2012
 * @author Raheel Merali
 */
public class TaskViewActivity extends AbstractTaskManagerActivity {


	/* The Task attributes that will be displayed */
	private static final TaskAttribute[] attributes = {TaskAttribute.NAME, TaskAttribute.ID};
	private static final int NAME_ATTRIBUTE_INDEX = 0;
	private static final int ID_ATTRIBUTE_INDEX = 1;

	private static final int DATE_DIALOG_ID = 0;
	private static final String[] FILTER_OPTIONS = {"View All", "Filter by Category", "Filter by Date", "Filter by Completed", "Filter by Not Completed"};
	private static final int FILTER_ALL = 0;
	private static final int FILTER_CATEGORY = 1;
	private static final int FILTER_DATE = 2;
	private static final int FILTER_COMPLETED = 3;
	private static final int FILTER_NOT_COMPLETED = 4;


	private OnClickListener buttonListener;
	private TaskManagerDBFacade facade;

	private Button map;
	private Button search;
	private Button delete;
	private Button add;
	private Button complete;

	/* The Android list that will display the list of Tasks */
	private ListView list;
	private TaskArrayAdapter taskListAdapter;
	private Spinner filterSpinner;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_view);
		facade = ((TaskManagerApplication)getApplication()).getFacade();

		list = (ListView) findViewById(R.id.list);
		filterSpinner = (Spinner) findViewById(R.id.category_filter);

		// Action Buttons
		map = (Button) findViewById(R.id.map);
		search = (Button) findViewById(R.id.search);
		delete = (Button) findViewById(R.id.delete);
		add = (Button) findViewById(R.id.add);
		complete = (Button) findViewById(R.id.complete);
		map.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_map));
		search.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_menu_search));
		delete.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_delete));
		add.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_input_add));

		// Button Listener
		buttonListener = new TaskViewButtonListener();
		add.setOnClickListener(buttonListener);
		delete.setOnClickListener(buttonListener);
		search.setOnClickListener(buttonListener);
		map.setOnClickListener(buttonListener);


		taskListAdapter = new TaskArrayAdapter(this, facade.getMasterListDisplayData());
		System.out.println("ahhhh");
		list.setAdapter(taskListAdapter);
		System.out.println("ahhhh");
		
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				try {
					String fullyQualifiedName = getString(R.string.ui_package_name) + getString(R.string.activity_task_info);
					Class<?> classToLaunch;
					classToLaunch = Class.forName(fullyQualifiedName);
					Intent classLaunchIntent = new Intent(TaskViewActivity.this, classToLaunch);
					Bundle b = new Bundle();
					b.putSerializable("task", (Serializable) new Task("test " + position, "test1", new Date(), 4534.3, 34543.4, Task.Recurrence.ONCE));
					classLaunchIntent.putExtras(b);
					startActivity(classLaunchIntent);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		});
		
//		filterSpinner.setOnItemSelectedListener(new FilterSpinnerListener());
//
//		setUpFilterSpinner();
	}

	public void onStart() {
		super.onStart();
//		displayAllTasks();
	}

	/**
	 * creates a drop down with categories as choices
	 */
	private void setUpFilterSpinner() {
		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, 
				android.R.layout.simple_spinner_item, 
				FILTER_OPTIONS);
		categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		filterSpinner.setAdapter(categoryAdapter);
	}

	private void displayTaskData(Object[] taskData) {
		taskListAdapter.clear();


		for (Object task : taskData) {
			taskListAdapter.add(task);
		}


		list.clearChoices();
	}

	/**
	 * updates the task list displayed
	 */
	private void displayAllTasks() {
		displayTaskData(facade.getMasterListDisplayData());
	}

//	private void displayFilteredTasks() {
//		displayTaskData(facade.getFilteredListDisplayData(attributes));
//	}
//
//	private void filterTaskListByCategory(String category) {
//		facade.resetFilteredList();
//		facade.filterByCategory(category);
//		displayFilteredTasks();
//	}
//
//	private void filterTaskListByDate(Date start) {
//		facade.resetFilteredList();
//		facade.filterByDueDate(start, new Date(Long.MAX_VALUE));
//		displayFilteredTasks();
//	}

	private DatePickerDialog.OnDateSetListener mDateSetListener =  
			new DatePickerDialog.OnDateSetListener() {  
		public void onDateSet(DatePicker view, int year,  
				int monthOfYear, int dayOfMonth) { 
			Date date = new Date();
			date.setYear(year);
			date.setMonth(monthOfYear);
			date.setDate(dayOfMonth);
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);

//			filterTaskListByDate(date);
		}
	}; 

	protected Dialog onCreateDialog(int id) {  
		switch (id) {  
		case DATE_DIALOG_ID:  
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH);
			int day = calendar.get(Calendar.DAY_OF_MONTH);

			return new DatePickerDialog(this, mDateSetListener, year, month, day);  
		}  
		return null;  

	}

	private class FilterSpinnerListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			switch(pos)
			{
			case FILTER_ALL:
				displayAllTasks();
				break;
				
			case FILTER_CATEGORY:
				AlertDialog.Builder categoryDialogBox = new AlertDialog.Builder(TaskViewActivity.this);
				categoryDialogBox.setTitle("Select a Category");
				categoryDialogBox.setItems(facade.getCategories(), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String selectedCategory = facade.getCategories()[which];
//						filterTaskListByCategory(selectedCategory);
						//                          FILTER_OPTIONS[FILTER_CATEGORY] = FILTER_OPTIONS[FILTER_CATEGORY] + " - " + selectedCategory;
						//                          int selectedItemPos = filterSpinner.getSelectedItemPosition();
						//                          setUpFilterSpinner();
						//                          filterSpinner.setSelection(selectedItemPos);
					}
				});
				categoryDialogBox.show();
				break;
				
			case FILTER_DATE:
				showDialog(DATE_DIALOG_ID);
				break;
				
			case FILTER_COMPLETED:
				break;
				
			case FILTER_NOT_COMPLETED:
				
				break;
			}

		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	}

	/**
	 * button listener
	 * @author Raheel Merali
	 *
	 */
	private class TaskViewButtonListener implements OnClickListener {


		/**
		 * handles button clicks
		 */
		public void onClick(View view) {
			int len;
			SparseBooleanArray checked;
			String[][] taskData;

			switch(view.getId()) {
			case R.id.add:
				try {
					String fullyQualifiedName = getString(R.string.ui_package_name) + getString(R.string.activity_new_task);
					Class<?> classToLaunch = Class.forName(fullyQualifiedName);
					Intent classLaunchIntent = new Intent(TaskViewActivity.this, classToLaunch);
					Bundle b = new Bundle();
					b.putSerializable("task", (Serializable) new Task("test1", "test1", new Date(), 4534.3, 34543.4, Task.Recurrence.ONCE));
					classLaunchIntent.putExtras(b);
					startActivity(classLaunchIntent);
				}
				catch(ClassNotFoundException e) {
					e.printStackTrace();
				}
				break;
			case R.id.delete:
//				len = list.getCount();
//				checked = list.getCheckedItemPositions();
//				taskData = facade.getMasterListDisplayData();
//				for (int i = 0; i < len; i++) {
//					if (checked.get(i)) {
//						facade.removeTask(Long.parseLong(taskData[i][ID_ATTRIBUTE_INDEX]));
//					}
//				}
//				displayAllTasks();
				break;
			case R.id.search:
				break;
			case R.id.map:
				break;
			case R.id.complete:
				//				 len = list.getCount();
				//				 checked = list.getCheckedItemPositions();
				//				 taskData = tm.getMasterListDisplayData(attributes);
				//				 for (int i = 0; i < len; i++) {
				//					 if (checked.get(i)) {
				//						 item = list.getChildAt(i);
				//						 //TextView someText = (TextView) item.findViewById(R.id.sometextview);
				//						 ((TextView)item).setText("Hi! I updated you manually!");
				//					 }
				//				 }
				//				 updateTaskList();
				// setPaintFlags(someLabel.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
				break;
			}
		}


	}

}